import React, { useState, useEffect } from 'react';
import { 
  Box, 
  Typography, 
  Grid, 
  Card, 
  CardContent, 
  CardMedia,
  Chip, 
  Avatar,
  Button,
  IconButton,
  Divider,
  CircularProgress,
  Alert,
  Fab,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  FormControl,
  InputLabel,
  Select,
  MenuItem
} from '@mui/material';
import { 
  DirectionsCar, 
  Speed, 
  Battery20, 
  LocationOn, 
  AccessTime,
  Add,
  Edit,
  Delete,
  Share,
  Warning,
  CheckCircle,
  Info
} from '@mui/icons-material';
import { apiRequest } from '../utils/api';
import { useNavigate } from 'react-router-dom';

const UserVehicleDashboard = () => {
  const [userVehicles, setUserVehicles] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [userData, setUserData] = useState(null);
  const [addVehicleDialog, setAddVehicleDialog] = useState(false);
  const [newVehicleData, setNewVehicleData] = useState({
    licensePlate: '',
    vin: '',
    model: '',
    year: '',
    color: '',
    ownerName: '',
    ownerEmail: ''
  });
  const navigate = useNavigate();

  useEffect(() => {
    loadUserVehicles();
  }, []);

  const loadUserVehicles = async () => {
    try {
      setLoading(true);
      
      // 获取当前用户信息
      const userResponse = await apiRequest.get('/api/auth/me');
      const userInfo = userResponse.data;
      setUserData(userInfo);

      // 使用专用API获取用户的车辆信息
      const vehiclesResponse = await apiRequest.get('/api/vehicles/my');
      const vehicles = vehiclesResponse.data || [];

      // 获取车辆的实时数据
      const vehiclesWithData = await Promise.all(
        vehicles.map(async (vehicle) => {
          try {
            const vehicleDataResponse = await apiRequest.get(`/api/vehicle-data/vehicle/${vehicle.id}`);
            const latestData = vehicleDataResponse.data[vehicleDataResponse.data.length - 1];
            return {
              ...vehicle,
              latestData: latestData || null
            };
          } catch (err) {
            return {
              ...vehicle,
              latestData: null
            };
          }
        })
      );

      setUserVehicles(vehiclesWithData);
      setError(null);
    } catch (err) {
      console.error('Error loading user vehicles:', err);
      setError('加载车辆信息失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  const handleAddVehicle = async () => {
    try {
      const vehicleData = {
        ...newVehicleData,
        ownerName: userData.firstName + ' ' + userData.lastName,
        ownerEmail: userData.email
      };

      const response = await apiRequest.post('/api/vehicles', vehicleData);
      const newVehicle = response.data;

      setAddVehicleDialog(false);
      setNewVehicleData({
        licensePlate: '',
        vin: '',
        model: '',
        year: '',
        color: '',
        ownerName: '',
        ownerEmail: ''
      });
      
      loadUserVehicles();
    } catch (err) {
      console.error('Error adding vehicle:', err);
      setError('添加车辆失败，请检查输入信息');
    }
  };

  const handleDeleteVehicle = async (vehicleId) => {
    if (window.confirm('确定要删除这辆车吗？此操作不可撤销。')) {
      try {
        console.log('Attempting to delete vehicle with ID:', vehicleId);
        // 添加更多的调试信息
        if (!vehicleId || typeof vehicleId !== 'string') {
          console.error('Invalid vehicle ID:', vehicleId);
          setError('无效的车辆ID');
          return;
        }
        
        // 使用正确导入的apiRequest
        const response = await apiRequest.delete(`/api/vehicles/${vehicleId}`);
        console.log('Delete vehicle successful:', response);
        loadUserVehicles();
      } catch (err) {
        console.error('Error deleting vehicle:', err.message);
        console.error('Error details:', err.response?.data || err);
        setError(`删除车辆失败: ${err.response?.data?.message || err.message || '未知错误'}`);
      }
    }
  };

  const getStatusColor = (status) => {
    switch (status) {
      case 'online': return 'success';
      case 'offline': return 'error';
      case 'warning': return 'warning';
      default: return 'default';
    }
  };

  const getStatusIcon = (status) => {
    switch (status) {
      case 'online': return <CheckCircle />;
      case 'offline': return <Warning />;
      case 'warning': return <Info />;
      default: return <Info />;
    }
  };

  const VehicleCard = ({ vehicle }) => (
    <Card sx={{ 
      height: '100%', 
      transition: 'transform 0.2s',
      '&:hover': { transform: 'translateY(-4px)' },
      boxShadow: 3
    }}>
      <CardContent>
        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', mb: 2 }}>
          <Box>
            <Typography variant="h6" component="div">
              {vehicle.licensePlate}
            </Typography>
            <Typography variant="body2" color="text.secondary">
              {vehicle.model} {vehicle.year}
            </Typography>
          </Box>
          <Chip 
            icon={getStatusIcon(vehicle.status || 'offline')}
            label={vehicle.status || '离线'}
            color={getStatusColor(vehicle.status || 'offline')}
            size="small"
          />
        </Box>

        <Box sx={{ mb: 2 }}>
          <Box sx={{ display: 'flex', alignItems: 'center', mb: 1 }}>
            <Speed fontSize="small" sx={{ mr: 1 }} />
            <Typography variant="body2">
              速度: {vehicle.latestData?.speed || 0} km/h
            </Typography>
          </Box>
          <Box sx={{ display: 'flex', alignItems: 'center', mb: 1 }}>
            <Battery20 fontSize="small" sx={{ mr: 1 }} />
            <Typography variant="body2">
              电量: {vehicle.latestData?.batteryLevel || 0}%
            </Typography>
          </Box>
          <Box sx={{ display: 'flex', alignItems: 'center', mb: 1 }}>
            <LocationOn fontSize="small" sx={{ mr: 1 }} />
            <Typography variant="body2" noWrap>
              位置: {vehicle.latestData?.location || '未知'}
            </Typography>
          </Box>
          <Box sx={{ display: 'flex', alignItems: 'center' }}>
            <AccessTime fontSize="small" sx={{ mr: 1 }} />
            <Typography variant="body2">
              更新: {vehicle.latestData ? new Date(vehicle.latestData.timestamp).toLocaleString() : '无数据'}
            </Typography>
          </Box>
        </Box>

        <Divider sx={{ my: 2 }} />

        <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
          <Button 
            size="small" 
            onClick={() => navigate(`/vehicles/${vehicle.id}`)}
            startIcon={<DirectionsCar />}
          >
            详情
          </Button>
          <Box>
            <IconButton 
              size="small" 
              onClick={() => navigate(`/vehicles/${vehicle.id}/edit`)}
              color="primary"
            >
              <Edit />
            </IconButton>
            <IconButton 
              size="small" 
              onClick={() => handleDeleteVehicle(vehicle.id)}
              color="error"
            >
              <Delete />
            </IconButton>
          </Box>
        </Box>
      </CardContent>
    </Card>
  );

  if (loading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '80vh' }}>
        <CircularProgress />
      </Box>
    );
  }

  return (
    <Box sx={{ p: 3 }}>
      <Box sx={{ mb: 4 }}>
        <Typography variant="h4" gutterBottom>
          我的车辆
        </Typography>
        <Typography variant="body1" color="text.secondary">
          欢迎回来，{userData?.firstName} {userData?.lastName}！
          您当前拥有 {userVehicles.length} 辆车
        </Typography>
      </Box>

      {error && (
        <Alert severity="error" sx={{ mb: 2 }} onClose={() => setError(null)}>
          {error}
        </Alert>
      )}

      <Grid container spacing={3}>
        {userVehicles.map((vehicle) => (
          <Grid item xs={12} sm={6} md={4} lg={3} key={vehicle.id}>
            <VehicleCard vehicle={vehicle} />
          </Grid>
        ))}
      </Grid>

      {userVehicles.length === 0 && (
        <Box sx={{ textAlign: 'center', py: 8 }}>
          <DirectionsCar sx={{ fontSize: 64, color: 'text.secondary', mb: 2 }} />
          <Typography variant="h6" color="text.secondary" gutterBottom>
            暂无车辆信息
          </Typography>
          <Typography variant="body1" color="text.secondary" paragraph>
            您还没有绑定任何车辆，点击下方按钮添加您的第一辆车
          </Typography>
          <Button 
            variant="contained" 
            size="large"
            onClick={() => setAddVehicleDialog(true)}
            startIcon={<DirectionsCar />}
          >
            添加车辆
          </Button>
        </Box>
      )}

      <Fab 
        color="primary" 
        aria-label="add" 
        sx={{ position: 'fixed', bottom: 16, right: 16 }}
        onClick={() => setAddVehicleDialog(true)}
      >
        <Add />
      </Fab>

      {/* 添加车辆对话框 */}
      <Dialog open={addVehicleDialog} onClose={() => setAddVehicleDialog(false)} maxWidth="sm" fullWidth>
        <DialogTitle>添加新车辆</DialogTitle>
        <DialogContent>
          <Box sx={{ pt: 2 }}>
            <TextField
              fullWidth
              label="车牌号"
              value={newVehicleData.licensePlate}
              onChange={(e) => setNewVehicleData({...newVehicleData, licensePlate: e.target.value})}
              margin="normal"
              required
            />
            <TextField
              fullWidth
              label="车辆识别号(VIN)"
              value={newVehicleData.vin}
              onChange={(e) => setNewVehicleData({...newVehicleData, vin: e.target.value})}
              margin="normal"
              required
            />
            <TextField
              fullWidth
              label="车型"
              value={newVehicleData.model}
              onChange={(e) => setNewVehicleData({...newVehicleData, model: e.target.value})}
              margin="normal"
              required
            />
            <TextField
              fullWidth
              label="年份"
              value={newVehicleData.year}
              onChange={(e) => setNewVehicleData({...newVehicleData, year: e.target.value})}
              margin="normal"
              required
            />
            <TextField
              fullWidth
              label="颜色"
              value={newVehicleData.color}
              onChange={(e) => setNewVehicleData({...newVehicleData, color: e.target.value})}
              margin="normal"
            />
          </Box>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setAddVehicleDialog(false)}>取消</Button>
          <Button onClick={handleAddVehicle} variant="contained">添加</Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default UserVehicleDashboard;